package leetcode.year2021.month9;


public class _23_03ReverseWords557 {
  public static void main(String[] args) {
    String a = "wed 2534";
    System.out.println(reverseWords(a));
    String b = "w";
    System.out.println(reverseWords(b));
  }

  public static String reverseWords(String s) {
    char[] chars = s.toCharArray();
    int start = 0;
    int end = 0;
    for (int i = 0; i < chars.length; i++) {
      if (chars[i] == ' ' && chars.length>1) {
        reverseCharArray(chars, start, end-1);
        start = i+1;
        end = i+1;
      } else if (i == chars.length-1){
        reverseCharArray(chars, start, end);
        start = i+1;
        end = i+1;
      } else {
        end ++;
      }
    }
    return new String(chars);
  }

  public static void reverseCharArray(char[] chars,int start,int end){
    int length = end - start + 1;
    for (int i = 0; i < length/2; i++) {
      char temp = chars[start + i];
      chars[start + i] = chars[end- i];
      chars[end- i] = temp;
    }
  }

  /**
   * 给定一个字符串，你需要反转字符串中每个单词的字符顺序，同时仍保留空格和单词的初始顺序。
   *
   *  
   *
   * 示例：
   *
   * 输入："Let's take LeetCode contest"
   * 输出："s'teL ekat edoCteeL tsetnoc"
   *  
   *
   * 提示：
   *
   * 在字符串中，每个单词由单个空格分隔，并且字符串中不会有任何额外的空格。
   *
   * 来源：力扣（LeetCode）
   * 链接：https://leetcode-cn.com/problems/reverse-words-in-a-string-iii
   * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
   */
}
